

package middlewareWeb;
import java.net.*;
import java.io.*;

/**
 *
 * @author myusy
 */
public class WorkerThread1 implements Runnable{

    protected DatagramSocket socketSrv;
    protected TQueueManager queueManager;
    protected Worker1 worker;
    protected ObjectInputStream ois;
    protected ObjectOutputStream oos;
    protected DatagramPacket packetIn;
    protected byte[] buffer;

    /**
     * Metodo costruttore
     */
    WorkerThread1(Worker1 worker,TQueueManager queueManager,DatagramSocket socketSrv,DatagramPacket packetIn,byte[] buffer){
            this.queueManager = queueManager;
            this.worker = worker;
            this.socketSrv = socketSrv;
            this.packetIn = packetIn;
            this.buffer = buffer;


    }
    /**
     * Override del metodo run
     */
    @Override
    public void run()
    {

        try
        {

                ByteArrayInputStream bin = new ByteArrayInputStream(packetIn.getData());

                ObjectInputStream oin = new ObjectInputStream(bin);

                TaskDescriptor tdRead = (TaskDescriptor)oin.readObject();

                int result = queueManager.enqueue(tdRead);
               String a= queueManager.toXML();
                String b= worker.IncrementaSequenzaOperazione().toString();
                String c=worker.IncrementaTaskInseriti().toString();
                int d=queueManager.getTQueue().size();

                /* Scrittura Log */
                LoggerMW logger= new LoggerMW();
                logger.creaLog(worker.getId(),worker.IncrementaClock(),
                        b,d,c,a,"Enqueue effettuata");

                queueManager.notifyObservers();
                worker.getProwyRM().getBufferProxy().enqueue(new InfoRM(worker.getId(),"enqueue", tdRead, worker.getWorkerAddress()),worker.getProwyRM().getClocks());

/*******************************************************************************
 **************** ESEGUIRE SCRITTURA SUL FILE DI LOG XML************************
 *******************************************************************************/

                oin.close();

                DatagramPacket replyPacket = new DatagramPacket(buffer,buffer.length,packetIn.getAddress(),packetIn.getPort());
                ByteArrayOutputStream bout = new ByteArrayOutputStream();
                DataOutputStream dout = new DataOutputStream(bout);
                dout.writeInt(result);
                buffer = bout.toByteArray();
                replyPacket.setData(buffer);
                replyPacket.setLength(buffer.length);
                socketSrv.send(replyPacket);
                bout.reset();

        }
        catch(Exception e)
        {
            System.out.println("Eccezione: " + e.getMessage());
        }
    }

}
